package com.andnux.android.activity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.andnux.android.MainApp;
import com.andnux.android.data.SystemUsers;
import com.andnux.android.databinding.ActivityMineSettingBinding;
import com.andnux.android.dialog.DialogFactory;
import com.andnux.android.network.DesignCloudApi;
import com.andnux.android.network.NotNullConsumer;
import com.andnux.android.network.Result;
import com.andnux.android.network.RetrofitClient;
import com.andnux.android.utils.GlideEngine;
import com.andnux.android.utils.ImageLoader;
import com.andnux.android.utils.StringUtils;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;

import java.io.File;
import java.util.ArrayList;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class MineSettingActivity extends BaseActivity<ActivityMineSettingBinding> {

    private static final int REQUEST_CODE = 0x88;
    private SystemUsers systemUsers;
    private DesignCloudApi api;
    private static final String[] items = {"男", "女", "未知"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        systemUsers = MainApp.getApp().getSystemUsers();
        api = RetrofitClient.getInstance().getServerApi();

        binding.toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        binding.hedImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PictureSelector.create(MineSettingActivity.this)
                        .openGallery(SelectMimeType.ofImage())
                        .setMaxSelectNum(1)
                        .setSelectionMode(SelectModeConfig.SINGLE)
                        .setImageEngine(GlideEngine.createGlideEngine())
                        .forResult(new OnResultCallbackListener<LocalMedia>() {
                            @Override
                            public void onResult(ArrayList<LocalMedia> result) {
                                for (LocalMedia s : result) {
                                    MultipartBody.Builder builder = new MultipartBody.Builder()
                                            .setType(MultipartBody.FORM);
                                    File file = new File(s.getRealPath());
                                    RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                                    builder.addFormDataPart("file", file.getName(), imageBody);
                                    upload(builder);
                                }
                            }

                            @Override
                            public void onCancel() {

                            }
                        });
            }
        });

        binding.nickname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogFactory.showInputDialog(MineSettingActivity.this, "请输入昵称",
                        systemUsers.getNickname(), "请输入昵称",
                        new DialogFactory.OnEditInputClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, String content) {
                                systemUsers.setNickname(content);
                                update();
                            }
                        });
            }
        });

        binding.email.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogFactory.showInputDialog(MineSettingActivity.this, "请输入邮箱",
                        systemUsers.getEmail(), "请输入邮箱",
                        new DialogFactory.OnEditInputClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, String content) {
                                systemUsers.setEmail(content);
                                update();
                            }
                        });
            }
        });

        binding.mobile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogFactory.showInputDialog(MineSettingActivity.this, "请输入手机号码",
                        systemUsers.getMobile(), "请输入手机号码",
                        new DialogFactory.OnEditInputClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, String content) {
                                systemUsers.setMobile(content);
                                update();
                            }
                        });
            }
        });

        binding.sex.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SystemUsers systemUsers = MainApp.getApp().getSystemUsers();
                DialogFactory.showSingleChoiceDialog(MineSettingActivity.this, "请选择性别",
                        items, StringUtils.toInt(systemUsers.getSex(), 0),
                        new DialogFactory.OnSingleClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                MineSettingActivity.this.systemUsers.setSex(which);
                                update();
                            }
                        });
            }
        });
        loadData();
    }

    private void upload(MultipartBody.Builder builder) {
        addDisposable(api.fileUpload(builder.build().parts())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new NotNullConsumer<Result<String>>() {
                    @Override
                    public void onSuccess(Result<String> result) {
                        systemUsers.setAvatar(result.getData());
                        update();

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        if (throwable != null) {
                            Toast.makeText(MineSettingActivity.this, throwable.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }));
    }

    private void update() {
        MainApp.getApp().setSystemUsers(systemUsers);
        addDisposable(api.userSave(systemUsers)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new NotNullConsumer<Result<Boolean>>() {
                    @Override
                    public void onSuccess(Result<Boolean> result) {
                        MainApp.getApp().setSystemUsers(systemUsers);
                        loadData();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        if (throwable != null) {
                            Toast.makeText(MineSettingActivity.this, throwable.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }));
    }

    private void loadData() {
        if (systemUsers != null) {
            ImageLoader.load(systemUsers.getAvatar(), binding.hedImage);
            binding.nicknametext.setText(systemUsers.getNickname());
            binding.emailtext.setText(systemUsers.getEmail());
            binding.mobiletext.setText(systemUsers.getMobile());
            int sex = StringUtils.toInt(systemUsers.getSex(), 0);
            binding.sextext.setText(items[sex]);
            binding.statustext.setText(StringUtils.toInt(systemUsers.getStatus()) == 0 ? "正常" : "停用");
        }
    }
}